<?php

class Crud_Form_Decorator_MultiColumn extends Zend_Form_Decorator_Abstract
{
	/**
	 * Count of column for visual view.
	 * 
	 * @var integer
	 */
	protected $_columnCount = 'auto';
	
	/**
	 * Get count of column for visual view.
	 * 
	 * @param integer $elementCount
	 * @return integer
	 */
	public function getColumnCount($elementCount = 10)
	{
		if ($this->_columnCount != 'auto') {
			return $this->_columnCount;
		}
		
		if ($elementCount < 7) {
			return 1;
		}
		
		if ($elementCount < 20) {
			return 2;
		}
		
		if ($elementCount < 40) {
			return 3;
		}
		
		if ($elementCount < 100) {
			return 4;
		}
		
		return 5;
	}
	
	/**
	 * Set count of columns.
	 * 
	 * @param integer $count
	 * @return void
	 */
	public function setColumnCount($count)
	{
		$this->_columnCount = $count;
	}
	
	/**
     * Decorate content and/or element
     *
     * @param  string $content
     * @return string
     * @throws Zend_Form_Decorator_Exception when unimplemented
     */
	public function render($content)
	{
		$array = explode("<label", $content);
		foreach ($array as $key => $value) {
			if (!trim($value)) {
				unset($array[$key]);
				continue;
			}
			$array[$key] = "<label$value";
		}
		
		$elementsCount = count($array);
		$columnCount = $this->getColumnCount($elementsCount);
		if ($columnCount == 1) return $content;
		
		$elementsInColumn = ceil($elementsCount / $columnCount);
		$separator = 1;
		$content = '<div class="multi-checkboxes">';
		$column = 0;
		foreach ($array as $value) {
			if ($separator == 1) {
				$column++;
				
				$class = 'multi-checkboxes-column';
				$content .= "<div class='$class'>";
			}
			
			$content .= $value;
			$separator++;
			
			if ($separator > $elementsInColumn) {
				$separator = 1;
				$content .= '</div>';
			}
		}

		if ($separator != 1) {
			$content .= '</div>';
		}
		
		$content .= '</div>';
		$content .= "<div class='clearfix'></div>";
		return $content;
		
	}
}
